package com.auto.api.core.type.json.torna;

import cn.torna.sdk.param.DocParamResp;
import com.auto.api.common.utils.JsonMapper;
import com.auto.api.core.type.TypeFactory;
import com.auto.api.core.type.defaultvalue.ValueTypeHandler;
import com.auto.api.core.util.BeanUtil;
import java.util.List;
import org.springframework.core.ResolvableType;

/**
 * @program:
 * @description: TornaCollectionApiResultJsonTypeHandler类型处理器
 * @author: liangshf
 * @create: 2020-09-24
 */
public class TornaCollectionApiResultJsonTypeHandler extends AbstractTornaApiResultJsonTypeHandler {

    @Override
    public boolean canCovert(ResolvableType resolvableType) {
        return resolvableType.isArray();
    }

    @Override
    public String getResultJson(ResolvableType resolvableType, List<DocParamResp> responseParams) {
        if (resolvableType.hasGenerics()) {
            ResolvableType genType = resolvableType.getGenerics()[0];
            Class rowClass = genType.getRawClass() == null ? String.class : genType.getRawClass();
            ValueTypeHandler typeHandler = TypeFactory.getTypeHandler(rowClass.getSimpleName());
            if (typeHandler != null) {
                /* 设置返回参数 */
                BeanUtil.getTornaSimpleListField(responseParams, rowClass.getSimpleName());
                return JsonMapper.toJson(responseParams);
            }
            DocParamResp array = BeanUtil.createTornaListField();
            List<DocParamResp> childrenList = BeanUtil.getTornaResultApi(genType);
            array.setChildren(childrenList);
            responseParams.add(array);
        } else {
            BeanUtil.getTornaSimpleListField(responseParams, String.class.getSimpleName());
        }
        return JsonMapper.toJson(responseParams);
    }
}